package com.tangtang.hystrix.provider.command;

import com.alibaba.fastjson.JSONObject;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.tangtang.hystrix.provider.utils.HttpClientUtils;
import com.tangtang.hystrix.provider.vo.ProductVO;

public class ProductCommand extends HystrixCommand<ProductVO> {


    private Long id;
    public ProductCommand(Long id){
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ProductGroup"))
                .andCommandKey(HystrixCommandKey.Factory.asKey("GetProductInfoCommand"))
                .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("GetProductInfoPool"))
                .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
                        .withCoreSize(15)
                        .withMaxQueueSize(10)
                        .withQueueSizeRejectionThreshold(10))
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
						.withCircuitBreakerRequestVolumeThreshold(30)
						.withCircuitBreakerErrorThresholdPercentage(40)
						.withCircuitBreakerSleepWindowInMilliseconds(3000)
						.withExecutionTimeoutInMilliseconds(500)
						.withFallbackIsolationSemaphoreMaxConcurrentRequests(30))
        );
        this.id = id;
    }

    @Override
    protected ProductVO run() throws Exception {
        String request = HttpClientUtils.sendGetRequest("http://127.0.0.1:8086/api/v1/product/"+id);
        return JSONObject.parseObject(request, ProductVO.class);
    }


    @Override
    protected ProductVO getFallback() {
        return super.getFallback();
    }
}
